const express = require('express');
const router = express.Router();
const User = require('../models/User');
const moment = require('moment');

// 用户列表页
router.get('/', async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 10;
    const searchParams = {
      id: req.query.id,
      username: req.query.username,
      createAt: req.query.createAt
    };

    const [users, total] = await Promise.all([
      User.findAll(page, limit, searchParams),
      User.count(searchParams)
    ]);

    const totalPages = Math.ceil(total / limit);

    res.render('users/list', {
      users,
      currentPage: page,
      totalPages,
      searchParams,
      moment
    });
  } catch (err) {
    res.status(500).send('服务器错误');
  }
});

// 添加用户页面
router.get('/add', (req, res) => {
  res.render('users/add');
});

// 处理添加用户
router.post('/add', async (req, res) => {
  try {
    await User.create(req.body);
    res.redirect('/users');
  } catch (err) {
    res.status(500).send('添加用户失败');
  }
});

// 编辑用户页面
router.get('/edit/:id', async (req, res) => {
  try {
    const users = await User.findAll(1, 1, { id: req.params.id });
    if (users.length === 0) {
      return res.status(404).send('用户不存在');
    }
    res.render('users/edit', { user: users[0] });
  } catch (err) {
    res.status(500).send('服务器错误');
  }
});

// 处理编辑用户
router.post('/edit/:id', async (req, res) => {
  try {
    await User.update(req.params.id, req.body);
    res.redirect('/users');
  } catch (err) {
    res.status(500).send('更新用户失败');
  }
});

// 删除用户
router.post('/delete/:id', async (req, res) => {
  try {
    await User.delete(req.params.id);
    res.redirect('/users');
  } catch (err) {
    res.status(500).send('删除用户失败');
  }
});

module.exports = router; 